define(["../common"], function() {
	
	var searchDoPath = g_shopDomain + "/memberVip/searchDo/json";
	var loadPrepaidsPath = g_shopDomain + "/memberPrepaid/list/json";
	var $form = $("#searchForm");
	var detailsItemTmp = $("#detailsItemTmp").html();
	
	loadjs(["validator"],function() {
		$form.validator({
			valid: search
		});
	});
	
	// 事件:查询会员
	$("[id^='submitBt_']").click(function() {
		$form.trigger('validate');
	});

	// 事件:查看充值记录
	$(document).on('click', "#listPrepaidBt", function() {
		loadPrepaids();
	});

	function search(form) {
		var name = $("#searchName").focus().val();
		if (!name || !$form.showMsg("正在查询...", 'load', true)) return;
		
		$("#hygl").html("");
		$.post(searchDoPath, {name: name}, function (data) {
			if (data.status !== 0) {
				$form.showMsg(data.message, 'error');
				return ;
			}
			$form.showMsg();
			var memberVip = data.result;
			var member = memberVip.member;
			
			// 记下memberId
			$("#hygl").data("memberId", member.memberId);
			
			// 性别 0保密 1男 2女
			var sex = member.sex;
			if (sex === 0) {
				sex = "保密";
			} else if (sex === 1) {
				sex = "男";
			} else {
				sex = "女";
			}
			
			var itemTmp = detailsItemTmp;
			itemTmp = itemTmp
			.replace(/\-\{name\}\-/g, member.name)
			.replace(/\-\{realName\}\-/g, member.realName?member.realName:"-")
			.replace(/\-\{sex\}\-/g, sex)
			.replace(/\-\{mobile\}\-/g, member.mobile?member.mobile:"-")
			.replace(/\-\{email\}\-/g, member.email?member.email:"-")
			.replace(/\-\{addTime\}\-/g, toDatetimeStr(memberVip.addTime))
			.replace(/\-\{balance\}\-/g, memberVip.balance);
			$("#hygl").html(itemTmp);
		});
	}

	function loadPrepaids() {
		
		var $list = $("#prepaidList");
		var $target = $("#hygl");
		
		$list.toggle();
		
		// 检查看是否需要加载(避免重复加载)
		var memberId = $target.data("memberId");
		$target.removeData("memberId");
		if (!memberId || !$target.showMsg("请稍候...", 'load', true)) return;
		
		$.post(loadPrepaidsPath, {"memberByMemberId.memberId": memberId, ps:10}, function(data) {
			if (data.status !== 0) {
				$target.showMsg(data.message, 'error');
				return;
			}
			$target.showMsg();
				
			var list = data.result;
			$list.show();
			if (!list) {
				$list.append("<tr><td colspan='3'>查无记录</td></tr>");
				return;
			}
			var given = "";
			for (var i = 0; i<list.length; i++) {
				given = list[i].given > 0 ? ("<span style='color:red'>+" + list[i].given+ "</span>") : "";
				$list.append("<tr><td>" + list[i].prepaid + given + "</td><td>" + toDatetimeStr(list[i].addTime) + "</td><td>" + list[i].memberByCheckerId.name + "</td></tr>");
			}
		});
	}

	function toDatetimeStr(timeStatemp){
		var date = new Date();
		date.setTime(timeStatemp);
		return date.format('yyyy-MM-dd hh:mm:ss');
	};
});
